<template>
  <Dialog title="退料【自动生成生产入库单】" v-model="dialogVisible">
    <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="100px"
        v-loading="formLoading"
    >
      <el-form-item label="物料条码" prop="planId">
        {{ formData.barcode }}
      </el-form-item>
      <el-form-item label="物料名称" prop="productName">
        {{ formData.productName }}
      </el-form-item>
      <el-form-item label="退料仓库" prop="inWarehouseId">
        <ErpSelectWarehouse v-model="formData.inWarehouseId" @select="setStockCount"/>

      </el-form-item>
      <el-form-item label="当前库存" prop="stockCount">
        {{ formData.stockCount }}
      </el-form-item>
      <el-form-item label="退料单位" prop="productUnitId">
        {{ formData.unitName }}
      </el-form-item>

      <el-form-item label="成本单价" prop="productName">
        {{ formData.productPrice }}
      </el-form-item>
      <el-form-item label="可退数量" prop="refundable">
        {{ formData.refundable }}
      </el-form-item>

      <el-form-item label="本次退料" prop="count">
        <el-input-number
          v-model="formData.count"
          placeholder="请输入退料数量"
          :min="0.001"
          :precision="3"
          :step="0.1"
          controls-position="right"
          class="!w-100%"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import {ProducePlanLog, ProducePlanLogApi} from '@/api/erp/produce/planLog'
import {StockApi} from "@/api/erp/stock/stock";
import ErpSelectWarehouse from "@/views/erp/stock/warehouse/components/ErpSelectWarehouse.vue";

/** ERP 生产计划日志 表单 */
defineOptions({name: 'ProducePlanMaterialReturn'})

const {t} = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formData = ref({
  id: undefined,
  planId: undefined,
  materialId: undefined,
  logType: undefined,
  linkId: undefined,
  outWarehouseId: undefined,
  inWarehouseId: undefined,
  productId: undefined,
  productName: undefined,
  count: undefined,
  productUnitId: undefined,
  status: undefined,
  remark: undefined,
  refundable:undefined
})
const formRules = reactive({
  planId: [{required: true, message: '生产计划单id不能为空', trigger: 'blur'}],
  inWarehouseId: [{required: true, message: '退料仓库不能为空', trigger: 'blur'}],
  count: [
    {required: true, message: '请输入本次退料数量', trigger: 'blur'},
    {type: 'number', message: '退料数量必须大于0', trigger: 'blur', min: 0.001},
    // 自定义校验：领料数量 ≤ 库存
    {
      validator: async (rule: any, value: number, callback: any) => {
        // 1. 未选择仓库时，先提示选仓库
        if (!formData.value.inWarehouseId) {
          return callback(new Error('请先选择退料仓库'));
        }
        // 4. 退料超过剩余量时，提示具体限制
        if (value >formData.value.refundable) {
          return callback(new Error(`退料超过剩余量（${formData.value.refundable}）`));
        }
        // 5. 校验通过
        callback();
      },
      trigger: ['blur', 'change'] // 输入框失焦、值变化时都触发校验
    }
  ]

})
const formRef = ref() // 表单 Ref

/** 打开弹窗 */
const open = async (row: any) => {
  resetForm()
  formData.value.planId = row.planId
  formData.value.materialId = row.id
  formData.value.productId = row.productId
  formData.value.barcode = row.productBarCode
  formData.value.productName = row.productName
  formData.value.count = 0
  formData.value.productPrice = row.price
  formData.value.productUnitId = row.unitId
  formData.value.unitName = row.unitName
  console.log(row)
  formData.value.refundable = row.pullCount - row.backCount - row.useCount
  dialogVisible.value = true
  formLoading.value = false
}
defineExpose({open}) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()

  // 提交请求
  formLoading.value = true
  try {
    console.log(formData.value)
    const data = formData.value as unknown as ProducePlanLog
    data.logType = "退料"
    await ProducePlanLogApi.createProducePlanLog(data)
    message.success(t('common.createSuccess'))

    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    planId: undefined,
    materialId: undefined,
    logType: undefined,
    linkId: undefined,
    outWarehouseId: undefined,
    inWarehouseId: undefined,
    productId: undefined,
    productName: undefined,
    count: undefined,
    productUnitId: undefined,
    status: undefined,
    remark: undefined
  }
  formRef.value?.resetFields()
}


const setStockCount = async () => {
  if (!formData.value.productId) {
    return
  }
  if (!formData.value.inWarehouseId) {
    return
  }
  let data = await StockApi.getStock2(formData.value.productId, formData.value.inWarehouseId)
  formData.value.stockCount = data?.count || 0
}
</script>
